package com.tl.common.photo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.widget.Toast;

import com.tl.common.util.DebugUtil;
import com.tl.common.util.StringUtils;

/**
 * 照片类帮助
 * 
 * Usage: 第一步: 初始化类 photoHelper = new PhotoHelper(this);
 * 
 * Step2:回调函数,2种调用方式
 * 
 * <pre>
 * photoHelper.fetchPhoto(new PhotoHelper.PhotoResultCallback() {
 *  public void onResult(Bitmap bitmap) {
 *   //.......
 *  }
 * }, FROM_CAMERA, new CropParam());
 * 
 * 第三步,在原activity的onActivityResult事件中跳转
 *  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 *   if ( requestCode ==PhotoHelper.FROM_CAMERA || requestCode ==PhotoHelper.FROM_MEDIA) {
 * 			photoHelper.onActivityResult(requestCode, resultCode, data);
 * 		}
 * }
 * </pre>
 * 
 * 第四部 清除剪切的图片缓存 PhotoHelper.clearCache();
 * 
 * @author BillyLi
 * @author liukai
 * 
 */
@SuppressLint("SimpleDateFormat")
public class PhotoHelper {

	public interface PhotoResultCallback {
		/**
		 * 返回结果
		 * 
		 * @param result
		 *            剪切或者拍照图片的略缩图
		 * @param imgpath
		 *            图片的存放地址
		 */
		void onResult(String result, Uri url);
	}

	private final String TAG = "PhotoHelper";
	public final static int FROM_CAMERA = 3000; // 拍照
	public final static int FROM_MEDIA = 3001; // 图库选择

	private PhotoResultCallback callback = null;
	private Activity context = null;
	private CropParam cropParam = null;
	private boolean needCrop = false;
	private int source;

	private String FILE_SAVEPATH = "";
	// = AppContext.FILE_SAVEPATH+ "Portrait/";

	private Uri mSaveUri;
	// private Uri cropUri;
	private String mSaveImage;
	// private String cropFileName;

	boolean isSDCard = true;
	int mScreenWidth = 480;
	int mScreenHeight = 800;

	public PhotoHelper(Activity context) {
		super();
		this.context = context;

		// 首先取得屏幕对象
		Display display = context.getWindowManager().getDefaultDisplay();
		// 获取屏幕的宽和高
		mScreenWidth = display.getWidth();
		mScreenHeight = display.getHeight();

	}

	public void setSavePath(String savePath) {
		FILE_SAVEPATH = savePath;

		// 判断是否挂载了SD卡
		try {
			String storageState = Environment.getExternalStorageState();
			if (storageState.equals(Environment.MEDIA_MOUNTED)) {
				File savedir = new File(FILE_SAVEPATH);
				if (!savedir.exists()) {
					savedir.mkdirs();
				}
			} else {
				isSDCard = false;
				// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
				return;
			}
		} catch (Exception e) {
			Toast.makeText(context, "无法创建图片保存目录,错误:" + e.getMessage(), -1)
					.show();
		}
	}

	public void setFileName(String fileName) {
		mSaveImage = fileName;
	}

	public String getImageFilePath() {
		String path = FILE_SAVEPATH + mSaveImage;
		boolean exits = new File(path).exists();

		return exits ? path : "";
	}

	public String getImageFileName() {
		String path = FILE_SAVEPATH + mSaveImage;
		boolean exits = new File(path).exists();
		return exits ? mSaveImage : "";
	}

	/**
	 * 开启相机或者图库
	 * 
	 * @param callback
	 *            回调函数
	 * @param photoSource
	 *            调用参数 FROM_CAMERA相机 FROM_MEDIA图库
	 */
	public void fetchPhoto(PhotoResultCallback callback, int photoSource) {
		fetchPhoto(callback, photoSource, null);
	}

	/**
	 * 开启相机或者图库,并且进行图片剪切
	 * 
	 * @param callback
	 *            回调函数
	 * @param source
	 *            调用参数:FROM_CAMERA相机 FROM_MEDIA图库
	 * @param cropParam
	 *            剪切参数,如果需要照片需要剪切就传入参数,否则为空
	 */
	public void fetchPhoto(PhotoResultCallback callback, int source,
			CropParam cropParam) {
		if (!isSDCard) {
			Toast.makeText(context, "无法保存拍照的图片，请检查SD卡是否挂载", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		this.callback = callback;
		this.needCrop = (cropParam != null);
		this.cropParam = cropParam;
		this.source = source;

		// 照片命名
		if (StringUtils.isEmpty(mSaveImage)) {
			String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date());
			mSaveImage = "app_" + timeStamp + ".jpg";
		}

		mSaveUri = Uri.fromFile(new File(FILE_SAVEPATH, mSaveImage));

		switch (this.source) {
		case FROM_CAMERA:
			startActionCamera(mSaveUri);
			break;
		case FROM_MEDIA:
			startActionPick(mSaveUri);

			break;
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK
				&& (requestCode == FROM_CAMERA || requestCode == FROM_MEDIA)) {
			return;
		}

		String defaultPath = FILE_SAVEPATH + mSaveImage;

		getImgpathFromIntent(data);

		if (StringUtils.isEmpty(defaultPath))
			return;

		if (needCrop) {
			File origFile = new File(defaultPath);
			boolean origExits = (defaultPath != null && origFile.exists());
			if (origExits) {
				Uri uri = Uri.fromFile(new File(defaultPath));
				if (uri != null) {
					startActionCrop(uri, mSaveUri);// 拍照后裁剪
				}
			}

			return;
		}

		switch (requestCode) {
		case FROM_CAMERA:
		case FROM_MEDIA:
			File saveFile = new File(defaultPath);
			boolean fileExits = defaultPath != null && saveFile.exists();
			if (fileExits) {
				// if (saveImg(getPicPath)) {
				callback.onResult(FILE_SAVEPATH + mSaveImage, null);
				// }
			}

			break;
		}

	}

	/**
	 * 相机拍照,保存为文件,如果使用data返回,图片质量太差
	 * 
	 * @param output
	 */
	private void startActionCamera(Uri output) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
		context.startActivityForResult(intent, FROM_CAMERA);
	}

	/**
	 * 选择图片
	 * 
	 * @param output
	 */
	private void startActionPick(Uri output) {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		intent.putExtra("output", output);
		context.startActivityForResult(Intent.createChooser(intent, "选择图片"),
				FROM_MEDIA);

	}

	/*
	*//**
	 * 选择图片裁剪
	 * 
	 * @param output
	 */
	/*
	 * private void startActionPickCrop(Uri output) { needCrop = false; Intent
	 * intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*");
	 * intent.putExtra(MediaStore.EXTRA_OUTPUT, output); intent.putExtra("crop",
	 * "true"); intent.putExtra("aspectX", cropParam.aspectX);// 裁剪框比例
	 * intent.putExtra("aspectY", cropParam.aspectY); intent.putExtra("outputX",
	 * cropParam.outputX);// 输出图片大小 intent.putExtra("outputY",
	 * cropParam.outputY);
	 * context.startActivityForResult(Intent.createChooser(intent, "选择图片"),
	 * FROM_MEDIA); }
	 */

	/**
	 * 拍照后裁剪
	 * 
	 * @param data
	 *            原始图片
	 * @param output
	 *            裁剪后图片
	 */
	private void startActionCrop(Uri data, Uri output) {
		needCrop = false;
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// cropParam.aspectX);// 裁剪框比例
		intent.putExtra("aspectY", 1);// cropParam.aspectY);
		intent.putExtra("outputX", cropParam.outputX);// 输出图片大小
		intent.putExtra("outputY", cropParam.outputY);
		context.startActivityForResult(intent, FROM_MEDIA);
	}

	/**
	 * 清空处理的图片
	 */
	public void clearCache() {
		File file = new File(FILE_SAVEPATH);
		if (file.isDirectory()) {
			File[] childFile = file.listFiles();
			for (File f : childFile) {
				f.delete();
			}
		}
	}

	/**
	 * 删除当前图片
	 */
	public void clearPic() {
		String defaultPath = FILE_SAVEPATH + mSaveImage;
		if (!StringUtils.isEmpty(defaultPath)) {
			File file = new File(defaultPath);
			if (file.exists()) {
				file.delete();
			}
		}
	}

	private void getImgpathFromIntent(Intent data) {

		// String protraitPath = FILE_SAVEPATH + cropFileName;

		// // 首先如果剪切的文件存在,优先返回剪切文件
		// File protraitFile = new File(protraitPath);
		// boolean protraitExits = (protraitPath != null &&
		// protraitFile.exists());
		//
		// if (protraitExits) {
		// return protraitPath;
		// }

		String defaultPath = FILE_SAVEPATH + mSaveImage;
		// 拍照或者直接获取的文件存在返回文件路径
		File origFile = new File(defaultPath);
		boolean origExits = (defaultPath != null && origFile.exists());
		if (origExits) {
			saveImg(defaultPath);
			return;
		}

		// 如果intent返回空,返回空目录
		if (data == null)
			return;

		// 取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，
		// 但是在拍照中有得机子呢Uri是空的，所以要特别注意
		// uri分为media和file
		Uri mImageCaptureUri = data.getData();
		if (mImageCaptureUri != null) {
			if (mImageCaptureUri.getScheme().compareTo("file") == 0) {

				// file:///开头的uri
				// String fileName = mImageCaptureUri.toString();
				// fileName = mImageCaptureUri.toString().replace("file://",
				// "");
				// // 替换file://
				// // 加上"/mnt"头
				// if (!fileName.startsWith("/mnt"))
				// fileName = "/mnt" + fileName;

				String fileName = mImageCaptureUri.getPath().toString();

				if (!StringUtils.isEmpty(fileName)) {
					saveImg(fileName);
				}

			}

			if (mImageCaptureUri.getScheme().toString().compareTo("content") == 0) {
				// content://开头的uri
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor actualimagecursor = context.managedQuery(
						mImageCaptureUri, proj, null, null, null);
				if (actualimagecursor != null) {
					int actual_image_column_index = actualimagecursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					actualimagecursor.moveToFirst();
					String img_path = actualimagecursor
							.getString(actual_image_column_index);

					if (!StringUtils.isEmpty(img_path)) {
						saveImg(img_path);
					}

				}

			}
		}

		// 如果返回的不是uri形式
		Bundle extras = data.getExtras();
		if (extras != null) {
			// 这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
			Bitmap image = extras.getParcelable("data");
			if (image != null) {
				saveImg(image);
			}
		}

		return;

	}

	/**
	 * 对图片进行压缩保存
	 * 
	 * @param filepath
	 * @return
	 */
	public boolean saveImg(String filepath) {
		boolean sucess = false;
		if (StringUtils.isEmpty(filepath)) {
			return false;
		}

		Bitmap pic = null;

		// 获取图片
		File file = new File(filepath);
		if (file.exists()) {
			pic = BitmapFactory.decodeFile(filepath);
		}

		sucess = saveImg(pic);

		return sucess;

	}

	/**
	 * 对图片进行压缩保存
	 * 
	 * @param filepath
	 * @return
	 */
	public boolean saveImg(File file) {
		boolean sucess = false;

		Bitmap pic = null;

		// 获取图片
		if (file.exists()) {
			pic = BitmapFactory.decodeFile(file.getPath());
		}

		sucess = saveImg(pic);

		return sucess;

	}

	/**
	 * 对图片进行压缩保存
	 * 
	 * @param filepath
	 * @return
	 */
	public boolean saveImg(Bitmap pic) {
		boolean sucess = false;

		try {
			// 如果图片大于屏幕分辨率.进行缩放
			if (pic != null
					&& (pic.getWidth() > (float) mScreenWidth || pic
							.getHeight() > (float) mScreenHeight)) {
				pic = ThumbnailUtils.extractThumbnail(pic, mScreenWidth,
						mScreenHeight);

			}

			// 保存为统一地址
			File fileSave = new File(FILE_SAVEPATH, mSaveImage);
			FileOutputStream out = new FileOutputStream(fileSave);
			if (pic.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
				out.flush();
				out.close();
			}
			pic.recycle();

			sucess = true;

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("FileNotFoundException");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("FileNotFoundException");
			e.printStackTrace();
		}

		return sucess;

	}

}